<template>
  <div class="goodsDetail-wrap">
    <Search></Search>
    <!-- <ShopHeader :shopInfo="goodsDetails.shopinfos || {}"></ShopHeader> -->
    <GoodsDetailNav :cateres="getcateres" :shop_id="shop_id"></GoodsDetailNav>
    <div class="shop-item-path">
      <!-- <div class="w">
        <Breadcrumb>
          <BreadcrumbItem to="/">首页</BreadcrumbItem>
          <BreadcrumbItem to="/goodsList">手机壳</BreadcrumbItem>
          <BreadcrumbItem>保护套</BreadcrumbItem>
        </Breadcrumb>
      </div> -->
    </div>
    <!-- 商品信息展示 -->
    <div class="main-wrap w">
      <!--      左侧商品详情页-->
      <div>
        <div class="item-detail-show">
          <div class="item-detail-left">
            <div class="item-detail-big-img">
              <img :src="getDetailBigImg" alt="22" />
            </div>
            <div class="item-detail-img-row">
              <div
                class="item-detail-img-small"
                v-for="(item, index) in goodsDetails.gpres"
                :key="index"
                @mouseover="showBigImg(index)"
              >
                <img :src="item.img_url" alt="" />
              </div>
            </div>
          </div>
          <div class="item-detail-right">
            <div class="item-detail-title">
              <p>
                {{ product.goods_name }}
              </p>
              <p>
                <span class="item-detail-goodstag" v-if="product.is_activity == 1">{{$t('秒杀')}}</span>
                <span class="item-detail-goodstag" v-if="product.is_activity == 2">{{$t('积分换购')}}</span>
                <span class="item-detail-goodstag" v-if="product.is_activity == 3">{{$t('拼团')}}</span>
              </p>
            </div>
            <div class="item-detail-price-row">
              <div class="item-price-left">
                <span class="item-price-title">{{ $t("市场价") }}：{{ `${product.zs_market_price}`}}</span>
                <span class="item-price">{{ product.currency_symbol }}{{
                  `${product.zs_shop_price}`
                }}</span>
              </div>
              <div class="item-price-right">
                <div class="item-remarks-sum">
                  <p class="item-remarks-sum-count">
                    {{ product.sale_number }}{{ $t("件") }}
                  </p>
                  <p class="item-remarks-sum-desc">{{ $t("销量") }}</p>
                </div>
              </div>
            </div>
            <!-- 选择颜色 -->
            <div class="item-select">
              <div class="item-select-column">
                <div
                  class="item-select-box"
                  v-for="(item, index) in specList"
                  :key="index"
                >
                  <div class="item-select-title">{{ item.title }}</div>
                    <div
                      class="item-select-selectItem u-m-8"
                      @click="
                        changeSpec(
                          item.title,
                          its.name,
                          its.able,
                          its.id,
                          index
                        )
                      "
                      v-for="(its, ins) in item.list" :key="ins"
                      :class="[
                        !its.able
                          ? 'item-select-selectItem-disable'
                          : its.check
                          ? 'item-select-selectItem-active'
                          : '',
                      ]"
                    >
                      <image
                        v-if="its.thumb"
                        class="item-select-img"
                        :src="its.thumb"
                      />
                      <span class="item-select-intro"> {{ its.name }}</span>
                    </div>
                  </div>
              </div>
            </div>
            <div class="add-buy-car-box">
              <div>
                <InputNumber
                  :min="1"
                  v-model="goodsNum"
                  size="large"
                  controls-outside
                ></InputNumber>
                <span class="goods-stock">
                  {{ $t("库存") + ":" + goodsDetails.pronum }}
                </span>
              </div>

              <div class="add-buy-car">
                <Button class="buy-button" type="error" size="large" @click="addCart()" v-if="![2,3].includes(product.is_activity)">{{ $t("加入购物车") }}</Button>
                <Button class="buy-button buy-now" size="large" @click="buyNow" v-if="product.is_activity == 2">{{ $t("立即兑换") }}</Button>
                <Button class="buy-button buy-now" size="large" @click="buyNow" v-else>{{ $t("立即购买") }}</Button>
              </div>
            </div>
          </div>
        </div>
        <Tabs class="detail-wrap">
          <TabPane :label="$t('商品详情')">
            <div class="detail-wrap-info" v-html="product.goods_desc"></div>
          </TabPane>
          <TabPane :label="$t('累计评论')">
              <div  class="detail-wrap-info" v-if="comment.length>0">
                <div class="detail-comment" v-for="(item, index) in comment" :key="index">
                  <div class="detail-comment-body">
                    <div class="detail-comment-left">
                      <Avatar size="40" :src="item.headimgurl" shape="circle" icon="logo-octocat"></Avatar>
                      <div>{{ $t(item.user_name) }}</div>
                    </div>
                    <div class="detail-comment-right">{{ $t(item.content) }}</div>
                  </div>
                  <div style="border-bottom: 1px dashed #ccc;"></div>
                </div>
              </div>
              <div v-else style="padding-left:20px;">{{ $t("暂无评论") }}</div>
          </TabPane>
        </Tabs>
      </div>

      <div>
        <ShopCard :shopInfo="goodsDetails.shopinfos" @focus="focus" @toService="toService" />

      </div>
    </div>
    <!-- 商品详细展示 -->
    <Spin size="large" fix v-if="isLoading"></Spin>
  </div>
</template>

<script>
import { Search, ShopCard, GoodsDetailNav, ShopHeader } from "@/components";
import store from "@/vuex/store";
import { mapState, mapActions } from "vuex";
//记录用户选择的属性
let strRadio = [];
export default {
  name: "GoodsDetail",
  beforeRouteEnter(to, from, next) {
    window.scrollTo(0, 0);
    next();
  },
  created() {
    // this.loadGoodsInfo();
    console.log(this.$store);
    const { goodsId: goods_id } = this.$route.query || {};
    this.goods_id = goods_id;
    this.getgoodsinfo(goods_id);
    this.goodsCommentList(goods_id);

  },
  data() {
    return {
      cateres:[],
      goodsDetails: {
        goodsinfo: {},
        shopinfos: {},
      },
      product: "", // 商品详情
      imgIndex: 0,
      goodsNum: 1,
      goods_id: "",
      specList: [],
      shop_id: '',
      skuList: [],
      selectSpec: {}, // 选择数据的对象 将已选的数据放在这个对象里面记录下来
      comment:[],
    };
  },
  methods: {
    ...mapActions(["addShoppingCart"]),
    showBigImg(index) {
      this.imgIndex = index;
    },
    
    goodsCommentList(goods_id) {
      this.$http.getGoodsCommentList({ goods_id: goods_id }).then((res) => {
        console.log(res)
        if(res.status ===200){
          this.comment = res.data.data
        }
      });
    },

    addCart() {
      const { goods_id, goodsNum: num } = this;
      const goods_attr = strRadio.join("_");
      const params = {
        goods_id,
        num,
        goods_attr,
      };
      this.addShoppingCart(params);
    },
    getshopcates(shop_id){
      this.$http.getshopcates({shop_id}).then(res=>{
        if(res.status===200){
          this.cateres = res.data.cateres
        }
      })
    },

    toService () {
      this.$http.getgoodsinfo({ goods_id: this.goods_id }).then((res) => {
        if (res.status === 200) {
          this.$root.$children[0].showIm({
            ...res.data.goodsinfo,
            userId: res.data.goodsinfo.shop_token,
            userName: res.data.goodsinfo.user_name,
            userAvatar: res.data.goodsinfo.headimgurl
          })
        }
      })
    },

    focus(coll_shops){
      console.log("关注店铺")
      console.log(coll_shops)
      if(coll_shops==0){
        this.$http.getshopcoll({shop_id:this.goodsDetails.goodsinfo.shop_id}).then(res=>{
          if(res.status===200){
            this.getgoodsinfo(this.goods_id);
            this.$Message.success(res.mess)
          }
        })
      }else{
        this.$http.getshopcancelcoll({shop_id:this.goodsDetails.goodsinfo.shop_id}).then(res=>{
          if(res.status===200){
            this.getgoodsinfo(this.goods_id);
            this.$Message.success(res.mess)
          }
        })
      }
    },
    getgoodsinfo(goods_id) {
      this.$http.getgoodsinfo({ goods_id: goods_id }).then((res) => {
        const { status, data } = res;
        if (status === 200) {
          this.$set(this, "goodsDetails", data);
          this.specList = data.formatSpecList;
          this.skuList = data.formatSkuList;
          this.product = data.goodsinfo;
          console.log({data});
          this.shop_id = data.shopinfos.id
          this.getshopcates(data.shopinfos.id)
          if (this.specList.length > 0) {
            // 初始化选择数据的对象
            this.specList.forEach((item) => {
              this.$set(this.selectSpec, item.title, "");
            });
            // 将规格数据处理成我们视图所需要的数据类型
            this.specList = this.specList.map((item) => {
              return {
                title: item.title,
                list: item.list.map((its) => {
                  return {
                    id: its.id,
                    name: its.title,
                    thumb: its.thumb,
                    // 判断是否可以选择
                    able: this.isAble(item.title, its.title), // 注释的调试看逻辑代码 false
                  };
                }),
              };
            });
          }
        }
      });
    },

    changeSpec(key, value, able, spec_item_id, index) {
      if (!able) return;
      if (this.selectSpec[key] === value) {
        this.selectSpec[key] = "";
      } else {
        this.selectSpec[key] = value;
      }
      console.log(this.selectSpec, key);
      // forEach循环改变原数组
      this.specList.forEach((item) => {
        item.list.forEach((its) => {
          its.able = this.isAble(item.title, its.name);
        });
      });

      let radioObject = this.specList;
      strRadio = [];
      let guigearr = [];

      for (var i = 0; i < radioObject[index].list.length; i++) {
        if (radioObject[index].list[i].id == spec_item_id) {
          if (radioObject[index].list[i].thumb) {
            this.product.thumb_url =
              radioObject[index].list[i].thumb + "?" + Math.random();
          } else {
            this.product.thumb_url = this.goodsThumb + "?" + Math.random();
          }
          this.$set(this.specList[index].list[i], "check", true);
        } else {
          this.$set(this.specList[index].list[i], "check", false);
        }
      }
      let specLengthArr = [];
      let temp = "";
      let tempStr = "";
      for (var i = 0; i < radioObject.length; i++) {
        specLengthArr.push(radioObject[i].list.length);
        for (var j = 0; j < radioObject[i].list.length; j++) {
          if (
            radioObject[i].list[j].check &&
            radioObject[i].list[j].check == true
          ) {
            strRadio.push(radioObject[i].list[j].id);
            if (
              !guigearr.includes(
                radioObject[i].title + ":" + radioObject[i].list[j].name
              )
            ) {
              guigearr.push(
                radioObject[i].title + ":" + radioObject[i].list[j].name
              );
            }
          }
        }
      }

      if (radioObject.length == strRadio.length) {
        // 将选中的商品规格id重新排序，与后端保持一致
        for (var i = 0; i < specLengthArr.length - 1; i++) {
          if (specLengthArr[i] > specLengthArr[i + 1]) {
            temp = specLengthArr[i];
            specLengthArr[i] = specLengthArr[i + 1];
            specLengthArr[i + 1] = temp;
            tempStr = strRadio[i];
            strRadio[i] = strRadio[i + 1];
            strRadio[i + 1] = tempStr;
          }
        }
        console.log(this.specList);
        this.selectText = this.$t("已选");
        this.$http
          .getGoodsPrice({
            goods_attr: strRadio.join("_"),
            goods_id: this.product.id,
            fangshi: this.isPT != 1 && this.product.is_activity == 3 ? 2 : 1,
            pin_number: this.choosePinNum,
          })
          .then((res) => {
            if (res.status == 200) {
              this.stock = res.data.attrinfos.stock;
              this.pin_id = res.data.pin_id;
              this.tuan_id = res.data.tuan_id;
              this.guige = guigearr.join(";");
              this.isJoin = false;
              this.userList = res.data.memberpinres;
              if (res.data.activity_info.length != 0) {
                this.activity_info = res.data.activity_info;
              }
              this.buyNum = 1;
              // if ((res.data.fangshi != 1 && this.isPT != 1) || !this.isPT || this.isPT == 2 &&
              // 	res.data.fangshi == 1) {
              // 	this.product.is_activity = res.data.attrinfos.is_activity
              // }

              this.product.goods_name = res.data.attrinfos.goods_name;
              this.product.zs_shop_price = res.data.attrinfos.zs_shop_price;
              // if(this.isPt = 1){
              // 	this.activity_info.dandu_button_price = res.data.attrinfos.zs_shop_price
              // }
              // if(this.isPt = 2){
              // 	this.product.zs_market_price = res.data.attrinfos.zs_shop_price
              // }
            }
          });
      }
    },
    // 判断规格是否可以被选择  核心函数 key当前的规格的title   value规格值
    isAble(key, value) {
      // 深拷贝 避免被影响
      var copySelectSpec = JSON.parse(JSON.stringify(this.selectSpec));
      // 用对象的好处就在这了 直接赋值当前验证项
      copySelectSpec[key] = value;
      // 用数组的 some 方法 效率高 符合条件直接退出循环
      let flag = this.skuList.some((item) => {
        // 条件判断 核心逻辑判断
        // console.log(item)
        var i = 0;
        // 这个for in 原理就是循环已经选中的 和 正在当前对比的数据 和 所有的sku对比 只有当前验证的所有项满足sku中的规格或者其他规格为空时 即满足条件 稍微有点复杂 把注释的调试代码打开就调试下就可以看懂了
        for (let k in copySelectSpec) {
          //  console.log(copySelectSpec[k])  // 注释的调试看逻辑代码
          if (
            copySelectSpec[k] != "" &&
            item.specs.includes(copySelectSpec[k])
          ) {
            // console.log(item)
            i++;
          } else if (copySelectSpec[k] == "") {
            i++;
          }
        }
        // 符合下面条件就退出了 不符合会一直循环知道循环结束没有符合的条件就 return false 了
        // console.log(i) // 注释的调试看逻辑代码
        return i == this.specList.length;
      });
      return flag;
    },
    async buyNow() {
      const { goods_id, goodsNum: num } = this;
      const goods_attr = strRadio.join("_");
      const buyWay = "1";
      if (this.product.hasoption) {
					let type = 'normal'
					// if (status == 1) {
					// 	type = 'normal'
					// } else if (status == 2) {
					// 	type = 'assemble'
					// }
					this.$http.getSkuList({
						goods_id: this.product.id,
						type
					}).then(res => {
						if (res.status == 200) {
							this.skuList = res.data

							this.specList = this.originSpecList
							if (this.specList.length > 0) {
								// 初始化选择数据的对象
								this.specList.forEach(item => {
									this.$set(this.selectSpec, item.title, "");
								})
								// 将规格数据处理成我们视图所需要的数据类型
								this.specList = this.specList.map(item => {
									return {
										title: item.title,
										list: item.list.map(its => {
											return {
												id: its.id,
												name: its.title,
												thumb: its.thumb,
												// 判断是否可以选择
												able: this.isAble(item.title,
													its
													.title
												) // 注释的调试看逻辑代码 false
											}
										})
									}
								})
							}
						}
					})

				}
      const { status, mess, data } = await this.$http.getpurbuy({
        num,
        goods_id,
        fangshi: buyWay,
        goods_attr,
      });

      if (status === 200) {
        this.$router.push({
          path: "/Order",
          query: {
            goods_id,
            num,
            pur_id: data.pur_id,
            fangshi: buyWay,
          },
        });
      }
    },
  },
  computed: {
    ...mapState(["isLoading"]),
    getcateres(){
      return this.cateres
    },
    getDetailBigImg() {
      return (
        this.goodsDetails["gpres"] &&
        this.goodsDetails["gpres"][this.imgIndex]["img_url"]
      );
    },

    getShowGoodsHeader() {
      const { goodsinfo, gpres, formatSkuList, pronum } = this.goodsDetails;
      return { ...goodsinfo, gpres, formatSkuList, pronum };
    },
  },
  components: {
    Search,
    ShopHeader,
    GoodsDetailNav,
    ShopCard,
  },
  store,
};
</script>

<style lang="scss" scoped>
.goodsDetail-wrap {
  background-color: #fff;
}
.shop-item-path {
  height: 38px;
  background-color: #fff;
  line-height: 38px;
  color: #2c2c2c;
}
.main-wrap {
  display: flex;
  justify-content: space-between;
}

.item-detail-show {
  margin: 15px 20px 15px 0;
  display: flex;
  flex-direction: row;
  padding: 10px 0;
  width: 100%;
}
.item-detail-left {
  width: 350px;
  margin-right: 30px;
}
.item-detail-big-img {
  width: 350px;
  height: 380px;
  cursor: pointer;
  overflow: hidden;
  &-fly {
    width: 10px;
    height: 10px;
    border-radius: 100px;
    background-color: pink;
  }
}
.item-detail-big-img img {
  width: 100%;
}
.item-detail-img-row {
  margin-top: 15px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  overflow: scroll;
  padding-bottom: 10px;
}
.item-detail-img-small {
  width: 60px;
  height: 60px;
  margin-right: 10px;
  border: 1px solid #eee;
  flex-shrink: 0;
  cursor: pointer;
}
.item-detail-img-small img {
  width: 100%;
}
/*商品选购详情*/
.item-detail-right {
  display: flex;
  flex-direction: column;
  margin-left: 20px;
}
.item-detail-title p {
  color: #333;
  font-size: 22px;
  font-weight: 500;
  margin-bottom: 10px;
}
.item-detail-goodstag{
  font-size: 12px;
  border: 1px solid #f00;
  border-radius: 5px;
  padding: 5px 10px;
}
.item-detail-express {
  font-size: 14px;
  padding: 2px 3px;
  border-radius: 3px;
  background-color: #e4393c;
  color: #fff;
}

/*价格详情等*/
.item-detail-price-row {
  padding: 10px 20px;
  margin-top: 10px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  background-color: #ff1e1e;
}
.item-price-left {
  display: flex;
  flex-direction: column;
}
.item-price-title {
  color: #fff;
  font-size: 16px;
  text-decoration: line-through;
}

.item-price {
  color: #ffff;
  font-size: 28px;
  font-weight: bold;
  cursor: pointer;
}

.item-remarks-sum {
  border-left: 1px solid #ff5d5d;
  text-align: center;
  padding-left: 20px;
  box-sizing: border-box;
  &-count {
    color: #fff;
    font-weight: 800;
    font-size: 20px;
  }
  &-desc {
    color: #eee;
    font-size: 12px;
  }
}

.item-select {
  display: flex;
  flex-direction: row;
  margin-top: 15px;
  &-selectItem{
    border: 1px solid #eee;
    padding:4px 6px;
    margin-right: 7px;
    margin-bottom: 7px;
    &-active{
      color: #e1251b;
      border: 1px solid;
    }
    &-disable{
      color:#999
    }
  }
}
.item-select-title {
  color: #999999;
  font-size: 14px;
  margin-right: 15px;

}
.item-select-column {
  display: flex;
  flex-direction: column;
}


.item-select-img {
  width: 20px;
}
.item-select-box {
  display: flex;
  flex-direction: row;
  align-items: center;
  padding: 3px 5px;
  margin-top: 8px;
  cursor: pointer;
  flex-wrap: wrap;
}


.item-select-img img {
  width: 100%;
}
.item-select-intro p {
  margin: 0px;
  padding: 5px 0;
  font-size: 12px;
}
.item-select-class {
  padding: 5px;
  margin-right: 8px;
  background-color: #f7f7f7;
  border: 0.5px solid #e7e3e7;
  cursor: pointer;
}

.item-select-disable {
  color: #999;
}
.item-select-class:hover {
  border: 0.5px solid #e3393c;
}
.add-buy-car-box {
  width: 100%;
  margin-top: 15px;
  border-top: 1px dotted #e7e3e7;
}
.add-buy-car {
  margin-top: 15px;
}
.mark-wrap {
  width: 20px;
  height: 20px;
  border-bottom: 24px solid red;
  border-left: 20px solid transparent;
  display: flex;
}
.buy-button {
  height: 50px;
  padding: 0 50px;
  margin-right: 20px;
  background-color: #e1251b;
}
.buy-now {
  background-color: transparent;
  color: #e1251b;
  border: 1px solid;
}
.goods-stock {
  margin-left: 10px;
}
.detail-wrap{
  margin-top: 30px;
  background-color: #f7f7f7;
  &-info{
    padding:20px
  }
}
.detail-comment-body{
  display:flex;
  flex-direction:row;
  justify-content:flex-start;
  padding-bottom:20px;
}
.detail-comment-left{
  width:180px;
  display:flex;
  flex-direction:column;
  justify-content:center;
  margin-top:10px;
}
.detail-comment-right{
  padding-top:20px;
}
/deep/ .ivu-tabs-ink-bar{
  top:0;
  height: 3px;
  background-color:#e3393c;
}
/deep/ .ivu-tabs-nav .ivu-tabs-tab{
  padding:18px 26px
}
/deep/ .ivu-tabs-nav .ivu-tabs-tab-active{
  color:#e3393c;
}
</style>
